const store = require('../utils/store')
// wx api 获得的设备信息
const systemInfo = store.getMobileInfo()

// 演示如何整合获取整合客户端的信息
const clientInfo = {
  model: systemInfo.model,
  os: systemInfo.system,
  screen: systemInfo.screenWidth + '*' + systemInfo.screenHeight,
  version: App.version,
}

module.exports = {
  myRequest: (url, data = {}, options = {}) => {
    // loading 是否展示加载信息
    // toast 是否展示提示信息
    // method 定义模式请求方式
    let { loading = true, toast = true, method = 'GET' } = options

    return new Promise((resolve, reject) => {
      if (loading) {
        wx.showLoading({
          title: '加载中',
          mask: true,
        })
      }
      const baseUrl = App.config.baseUrl
      wx.request({
        url: baseUrl + url,
        data,
        header: {
          // 头部信息传递 客户端信息
          clientInfo: JSON.stringify(clientInfo),
        },
        method,
        success: (result) => {
          // {code:0,data:'',message:''}
          const res = ressult.data
          if (res.code === 0) {
            if (loading) {
              wx.hideLoading()
            }
            resolve(res.data)
          } else {
            if (toast) {
              wx.showToast({
                title: res.message,
                mask: true,
                icon: 'none',
              })
            }
          }
        },
        fail: (err) => {
          wx.showToast({
            title: err.errMsg,
            icon: 'none',
          })

          reject(err)
        },
      })
    })
  },
}
